/**
 * Copyright (c) 2012-2014 All Rights Reserved.
 */
package com.easy.framwork.jdbc;

import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author wy
 * @version v 0.1 2014-1-2 下午8:40:27 wy Exp $
 */
public abstract class AbstractQueryHelper {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 创建一个 PreparedStatement
     * 
     * @param conn
     * @param sql
     * @return
     * @throws SQLException
     */
    public PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException {

        return conn.prepareStatement(sql);
    }

    /**
     * 填充预查询参数
     * 
     * @param stmt
     * @param params
     * @throws SQLException
     */
    public void fillStatement(PreparedStatement stmt, Object... params) throws SQLException {

        ParameterMetaData pmd = stmt.getParameterMetaData();
        int stmtCount = pmd.getParameterCount();
        int paramsCount = params == null ? 0 : params.length;

        if (stmtCount != paramsCount) {
            throw new SQLException("Wrong number of parameters: expected " + stmtCount
                                   + ", was given " + paramsCount);
        }

        if (params == null) {
            return;
        }
        for (int i = 0; i < params.length; i++) {
            if (params[i] != null) {
                stmt.setObject(i + 1, params[i]);
            } else {
                stmt.setNull(i + 1, Types.VARCHAR);
            }
        }
    }

    /**
     * 异常重新处理
     * 
     * @param cause
     * @param sql
     * @param params
     * @throws SQLException
     */
    public void throwSQLException(SQLException cause, String sql, Object... params)
                                                                                   throws SQLException {

        String causeMessage = cause.getMessage();
        if (causeMessage == null) {
            causeMessage = "";
        }
        StringBuffer msg = new StringBuffer(causeMessage);

        msg.append(" Query: ");
        msg.append(sql);
        msg.append(" Parameters: ");
        if (params == null) {
            msg.append("[]");
        } else {
            msg.append(Arrays.deepToString(params));
        }

        SQLException e = new SQLException(msg.toString(), cause.getSQLState(), cause.getErrorCode());

        throw e;
    }

    /**
     * log the sql
     * 
     * @param queryTime
     * @param sql
     * @param params
     */
    public void logSQL(long queryTime, String sql, Object... params) {
        log.debug("Query:{} [QueryTime={}]", sql, queryTime);
        log.debug("Parameters:{}", params == null ? "" : Arrays.deepToString(params));
    }
}
